<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>个人中心 - 校园二手交易平台</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #f5f5f5;
      font-size: 18px;
    }
    .container {
      max-width: 1000px;
      margin: 50px auto;
      background: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .header {
      text-align: center;
      margin-bottom: 30px;
    }
    .profile-info {
      margin-bottom: 20px;
    }
    .profile-info label {
      font-weight: bold;
      font-size: 1.1em;
    }
    .btn {
      padding: 10px 20px;
      background: #667eea;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    .btn:hover {
      background: #5a6fd8;
    }
    /* Style for the return to home button */
    .btn-outline {
      padding: 10px 15px;
      background-color: transparent;
      color: #667eea;
      border: 1px solid #667eea;
      border-radius: 5px;
      text-decoration: none;
      display: inline-block; /* Treat link as button */
      transition: background-color 0.3s, color 0.3s;
    }
    .btn-outline:hover {
      background-color: #667eea;
      color: white;
    }
    /* Styles for the modal */
    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 101; /* Sit on top */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
      align-items: center; /* Center vertically */
      justify-content: center; /* Center horizontally */
    }
    .modal-content {
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.2);
      max-width: 500px;
      width: 90%;
    }
    .modal-content h3 {
      margin-top: 0;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
      margin-bottom: 20px;
      text-align: center;
    }
    .modal-content label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
    .modal-content input[type="text"], .modal-content input[type="email"], .modal-content input[type="tel"] {
      width: 100%;
      padding: 8px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    .modal-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 20px;
    }
  </style>
</head>
<body>
<!-- Return Home Button outside the container -->
<a href="index.html" class="btn-outline" style="position: absolute; top: 20px; left: 20px; z-index: 100;">返回首页</a>

<div class="container">
  <div class="header">
    <h2>个人中心</h2>
  </div>
  <div class="profile-info">
    <div><label>昵称:</label> <span id="nickname"></span></div>
    <div><label>学号:</label> <span id="studentId"></span></div>
    <div><label>真实姓名:</label> <span id="realName"></span></div>
    <div><label>邮箱:</label> <span id="email"></span></div>
    <div><label>电话:</label> <span id="phone"></span></div>
  </div>
  <div style="text-align: center; margin-top: 30px;">
    <button class="btn-outline" id="editProfileBtn" style="margin-right: 10px;">编辑信息</button>
    <button class="btn" onclick="logout()">退出登录</button>
  </div>
</div>

<!-- Edit Profile Modal -->
<div id="editProfileModal" class="modal">
  <div class="modal-content">
    <h3>编辑个人信息</h3>
    <form id="editProfileForm">
      <input type="hidden" id="editUserId">
      <div>
        <label for="editNickname">昵称:</label>
        <input type="text" id="editNickname" required>
      </div>
      <div>
        <label for="editStudentId">学号:</label>
        <input type="text" id="editStudentId" required readonly style="background-color: #eee;">
      </div>
      <div>
        <label for="editRealName">真实姓名:</label>
        <input type="text" id="editRealName" required readonly style="background-color: #eee;">
      </div>
      <div>
        <label for="editEmail">邮箱:</label>
        <input type="email" id="editEmail" required>
      </div>
      <div>
        <label for="editPhone">电话:</label>
        <input type="tel" id="editPhone" required>
      </div>
      <div class="modal-buttons">
        <button type="button" class="btn-outline" onclick="closeEditProfileModal()">取消</button>
        <button type="submit" class="btn">保存</button>
      </div>
    </form>
  </div>
</div>

<script>
  function checkLogin() {
    const userData = localStorage.getItem('user');
    if (!userData) {
      window.location.href = 'login.html';
      return;
    }
    const user = JSON.parse(userData);
    document.getElementById('nickname').textContent = user.nickname;
    document.getElementById('studentId').textContent = user.studentId;
    document.getElementById('realName').textContent = user.realName;
    document.getElementById('email').textContent = user.email;
    document.getElementById('phone').textContent = user.phone;
    
    // Add event listener to the edit button
    document.getElementById('editProfileBtn').onclick = () => openEditProfileModal(user);
  }

  function logout() {
    localStorage.removeItem('user');
    window.location.href = 'login.html';
  }

  // Functions to control the edit profile modal
  function openEditProfileModal(user) {
    document.getElementById('editProfileModal').style.display = 'flex';
    // Populate the form with user data
    document.getElementById('editUserId').value = user.userId;
    document.getElementById('editNickname').value = user.nickname;
    document.getElementById('editStudentId').value = user.studentId;
    document.getElementById('editRealName').value = user.realName;
    document.getElementById('editEmail').value = user.email;
    document.getElementById('editPhone').value = user.phone;
  }

  function closeEditProfileModal() {
    document.getElementById('editProfileModal').style.display = 'none';
  }

  // Handle form submission (will be implemented in a later step)
  document.getElementById('editProfileForm').addEventListener('submit', async function(event) {
      event.preventDefault(); // Prevent default form submission
      
      const userId = document.getElementById('editUserId').value;
      const updatedUser = {
          userId: userId, // Include userId in the body for backend convenience
          nickname: document.getElementById('editNickname').value,
          studentId: document.getElementById('editStudentId').value,
          realName: document.getElementById('editRealName').value,
          email: document.getElementById('editEmail').value,
          phone: document.getElementById('editPhone').value
      };

      console.log('Updated user data:', updatedUser);

      // Send updatedUser to backend API to save
      try {
          const response = await fetch(`/api/users/${userId}`, {
              method: 'PUT',
              headers: {
                  'Content-Type': 'application/json',
                  'X-Current-User-Id': userId // Add user ID to header
              },
              body: JSON.stringify(updatedUser)
          });

          if (response.ok) {
              alert('个人信息更新成功！');
              closeEditProfileModal();
              // Optionally reload user data or update displayed info
              // Update localStorage with the new user data
              const currentUserData = JSON.parse(localStorage.getItem('user'));
              const updatedUserData = { ...currentUserData, ...updatedUser };
              localStorage.setItem('user', JSON.stringify(updatedUserData));
              checkLogin(); // Refresh displayed info on the page
          } else {
              const errorText = await response.text();
              alert(`更新失败: ${errorText}`);
              console.error('更新失败:', errorText);
          }
      } catch (error) {
          console.error('更新失败:', error);
          alert('更新失败，发生网络错误。');
      }
  });

  window.addEventListener('load', checkLogin);
</script>
</body>
</html>